<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Common Modules Source: control/Loading.js</title>

	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">

</head>

<body>

<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="index.html">Common Modules</a>
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
        </button>
	</div>
	<div class="navbar-collapse collapse" id="topNavigation">
		<ul class="nav navbar-nav">
			
			<li class="dropdown">
				<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="Base.html">Base</a></li><li><a href="Event.html">Event</a></li><li><a href="Html.html">Html</a></li><li><a href="Internal.html">Internal</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li>
				</ul>
			</li>
			
			<li class="dropdown">
				<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="global.html#addClass">addClass</a></li><li><a href="global.html#addListener">addListener</a></li><li><a href="global.html#arrayRemove">arrayRemove</a></li><li><a href="global.html#clear">clear</a></li><li><a href="global.html#create">create</a></li><li><a href="global.html#createHidden">createHidden</a></li><li><a href="global.html#empty">empty</a></li><li><a href="global.html#EventType">EventType</a></li><li><a href="global.html#findListener">findListener</a></li><li><a href="global.html#firstUpperToCase">firstUpperToCase</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#getChildByTagName">getChildByTagName</a></li><li><a href="global.html#getClass">getClass</a></li><li><a href="global.html#getDomEventKey">getDomEventKey</a></li><li><a href="global.html#getElementsByClassName">getElementsByClassName</a></li><li><a href="global.html#getListeners">getListeners</a></li><li><a href="global.html#getrandom">getrandom</a></li><li><a href="global.html#getStyle">getStyle</a></li><li><a href="global.html#getuuid">getuuid</a></li><li><a href="global.html#hasClass">hasClass</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#layerConfigDefautls">layerConfigDefautls</a></li><li><a href="global.html#listen">listen</a></li><li><a href="global.html#listenOnce">listenOnce</a></li><li><a href="global.html#logo">logo</a></li><li><a href="global.html#OL_Style_Type">OL_Style_Type</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeClass">removeClass</a></li><li><a href="global.html#removeListener">removeListener</a></li><li><a href="global.html#removeListeners">removeListeners</a></li><li><a href="global.html#setClass">setClass</a></li><li><a href="global.html#splitWords">splitWords</a></li><li><a href="global.html#stamp">stamp</a></li><li><a href="global.html#toBack">toBack</a></li><li><a href="global.html#toFront">toFront</a></li><li><a href="global.html#trim">trim</a></li><li><a href="global.html#unListen">unListen</a></li><li><a href="global.html#unlistenAll">unlistenAll</a></li><li><a href="global.html#unListenByKey">unListenByKey</a></li><li><a href="global.html#upperFirstChart">upperFirstChart</a></li>
				</ul>
			</li>
			
		</ul>
        
            <div class="col-sm-3 col-md-3">
                <form class="navbar-form" role="search">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
                        <div class="input-group-btn">
                            <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
                        </div>
                    </div>
                </form>
            </div>
        
	</div>

</div>
</div>


<div class="container" id="toc-content">
<div class="row">

	
	<div class="col-md-12">
	
		<div id="main">
			

		<h1 class="page-title">Source: control/Loading.js</h1>
    
<section>
    <article>
        <pre
            class="sunlight-highlight-javascript linenums">/**
 * @desc 全局地图加载loading
 */
import {
    ol
} from '../constants'
import {BASE_CLASS_NAME} from '../constants'
import * as htmlUtils from '../utils/domUtils'
import '../asset/scss/loading.scss'
ol.control.Loading = function (params) {
  /**
   * 当前配置
   * @type {*}
   */
  this.options = params || {}
  /**
   * 地图事件
   * @type {Array}
   */
  this.mapListeners = []
  /**
   * 切片事件
   * @type {Array}
   */
  this.tileListeners = []
  /**
   * 加载状态
   * @type {boolean}
   * @private
   */
  this.loadStatus_ = false
  /**
   * 是否第一次渲染
   * @type {boolean}
   */
  this.isFirstRander = true
  /**
   * 加载进度
   * @type {[*]}
   * @private
   */
  this.loadProgress_ = [0, 1]
  // 窗口挂件类型（现有支持gif和进度条）
  if (this.options['widget']) {
    if (['animatedGif', 'progressBar'].indexOf(this.options['widget']) === -1) {
      throw Error('不支持的挂件类型')
    } else {
      this.widget = (this.options['widget'] ? this.options['widget'] : 'animatedGif')
    }
  }
  // 进度条模式
  if (this.options['progressMode']) {
    if (['tile', 'layer'].indexOf(this.options['progressMode']) === -1) {
      throw Error('不支持的进度条模式')
    }
    this.loadProgressByTile_ = ((this.options['progressMode'] === 'layer') ? !(this.options['progressMode'] === 'layer') : true)
  }
  // 是否显示loading面板
  this.showPanel = (typeof this.options['showPanel'] === 'boolean') ? this.options['showPanel'] : true
  let className = (this.options.className !== undefined ? this.options.className : 'gmap-loading-panel')
  // DOM
  let elementDom = (this.widget === 'animatedGif') ? 'span' : 'progress'
  let element = htmlUtils.create(elementDom, (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE))
  if (this.widget === 'progressBar') {
    // element progress bar for old browsers
    let div = htmlUtils.create('div', 'gmap-progress-bar')
    htmlUtils.create('span', '', div)
  }
  this.onCustomStart = (this.options['onStart'] ? this.options['onStart'] : false)
  this.onCustomProgress = (this.options['onProgress'] ? this.options['onProgress'] : false)
  this.onCustomEnd = (this.options['onEnd'] ? this.options['onEnd'] : false)
  ol.control.Control.call(this, {
    element: element,
    target: this.options['target']
  })
}

ol.inherits(ol.control.Loading, ol.control.Control)

/**
 * 设置
 */
ol.control.Loading.prototype.setup = function () {
  this.setDomPosition()
  this.resize()
  let pointerDown = this.getMap().on('pointerdown', () => {
    this.hide()
  })
  let beforeRander = this.getMap().on('precompose', () => {
    if (this.isFirstRander) {
      this.isFirstRander = false
      this.registerLayersLoadEvents_()
      this.show()
      if (this.onCustomStart) {
        let args = []
        this.onCustomStart.apply(this, args)
      }
    }
  })
  let afterRander = this.getMap().on('postrender', () => {
    this.updateLoadStatus_()
    if (this.loadStatus_) {
      if (this.onCustomEnd) {
        let args = []
        this.onCustomEnd.apply(this, args)
      }
      this.hide()
    }
  })
  this.mapListeners.push(pointerDown)
  this.mapListeners.push(beforeRander)
  this.mapListeners.push(afterRander)
}

/**
 * 设置dom位置
 */
ol.control.Loading.prototype.setDomPosition = function () {
  let size = this.getMap().getSize()
  let domSize = [this.element.clientWidth, this.element.clientHeight]
  this.element.style.left = String(Math.round((size[0] - domSize[0]) / 2)) + 'px'
  this.element.style.bottom = String(Math.round((size[1] - domSize[1]) / 2)) + 'px'
}

/**
 * 窗口变化事件
 */
ol.control.Loading.prototype.resize = function () {
  let resizeEvt = (('orientationchange' in window) ? 'orientationchange' : 'resize')
  let doc = window.document
  let that = this
  window.addEventListener(resizeEvt, function () {
    setTimeout(function () {
      that.setDomPosition()
    }, 50)
  }, false)
  window.addEventListener('pageshow', function (e) {
    if (e.persisted) {
      setTimeout(function () {
        that.setDomPosition()
      }, 50)
    }
  }, false)
  if (doc.readyState === 'complete') {
    setTimeout(function () {
      that.setDomPosition()
    }, 50)
  } else {
    doc.addEventListener('DOMContentLoaded', function (e) {
      setTimeout(function () {
        that.setDomPosition()
      }, 50)
    }, false)
  }
}

/**
 * 获取进度
 * @param source
 * @returns {boolean}
 * @private
 */
ol.control.Loading.prototype.updateSourceLoadStatus_ = function (source) {
  return (Math.round(source.loaded / source.loading * 100) === 100)
}

/**
 * 注册图层事件
 * @param layer
 * @private
 */
ol.control.Loading.prototype.registerLayerLoadEvents_ = function (layer) {
  let that = this
  layer.getSource().on('tileloadstart', function (event) {
    if (that.loadStatus_) {
      that.loadStatus_ = false
      that.loadProgress_ = [0, 1]
      if (that.widget === 'progressBar') {
        that.element.value = that.loadProgress_[0]
        that.element.max = that.loadProgress_[1]
      }
      that.show()
      if (that.onCustomStart) {
        let args = []
        that.onCustomStart.apply(that, args)
      }
    }
    this.loading = (this.loading) ? this.loading + 1 : 1
    this.isLoaded = that.updateSourceLoadStatus_(this)
    if (that.loadProgressByTile_) {
      this.loadProgress_[1] += 1
      if (this.widget === 'progressBar') {
        that.element.max = that.loadProgress_[1]
        let progressBarDiv = that.element.getElementsByClassName('gmap-progress-bar')
        if (progressBarDiv.length > 0) progressBarDiv[0].children()[0].width = String(parseInt(100 * that.progress(), 0)) + '%'
      }
    }
  })
  layer.getSource().on(['tileloadend', 'tileloaderror'], function (e) {
    if (e.tile.getState() === 3) {
      console.warn('Loading tile failed for resource \'' + e.tile.src_ + '\'')
    }
    this.loaded = (this.loaded) ? this.loaded + 1 : 1
    this.isLoaded = that.updateSourceLoadStatus_(this)
    if (that.loadProgressByTile_) {
      that.loadProgress_[0] += 1
      if (that.widget === 'progressBar') {
        that.element.value = that.loadProgress_[0]
        let progressBarDiv = this.element.getElementsByClassName('gmap-progress-bar')
        if (progressBarDiv.length > 0) {
          progressBarDiv[0].children()[0].width = String(parseInt(100 * that.progress(), 0)) + '%'
        }
      }
      if (that.onCustomProgress) {
        that.onCustomProgress.apply(that, that.loadProgress_)
      }
    }
  })
}

/**
 * 注册全局图层事件
 * @private
 */
ol.control.Loading.prototype.registerLayersLoadEvents_ = function () {
  let groups = this.getMap().getLayers().getArray()
  for (let i = 0; i &lt; groups.length; i++) {
    let layer = groups[i]
    if (layer instanceof ol.layer.Group) {
      let layers = layer.getLayers().getArray()
      for (let j = 0; j &lt; layers.length; j++) {
        let l = layers[j]
        if (!(l instanceof ol.layer.Vector)) {
          this.tileListeners.push(this.registerLayerLoadEvents_(l))
        }
      }
    } else if (layer instanceof ol.layer.Layer) {
      if (!(layer instanceof ol.layer.Vector)) {
        this.tileListeners.push(this.registerLayerLoadEvents_(layer))
      }
    }
  }
}

/**
 * 更新加载状态
 * @private
 */
ol.control.Loading.prototype.updateLoadStatus_ = function () {
  let loadStatusArray = []
  let groups = this.getMap().getLayers().getArray()
  for (let i = 0; i &lt; groups.length; i++) {
    let layer = groups[i]
    if (layer) {
      if (layer instanceof ol.layer.Group) {
        let layers = layer.getLayers().getArray()
        for (let j = 0; j &lt; layers.length; j++) {
          let l = layers[j]
          if (l &amp;&amp; l.getSource() &amp;&amp; !(l instanceof ol.layer.Vector) &amp;&amp; l.getSource().hasOwnProperty('isLoaded')) {
            loadStatusArray.push(l.getSource().isLoaded)
          }
        }
      } else if (layer.getSource() &amp;&amp; layer.getSource().hasOwnProperty('isLoaded')) {
        loadStatusArray.push(layer.getSource().isLoaded)
      }
    }
  }
  this.loadStatus_ = (loadStatusArray.indexOf(false) === -1) &amp;&amp; (loadStatusArray.indexOf(true) !== -1)
  if (!this.loadProgressByTile_) {
    // progress
    let count = {}
    loadStatusArray.forEach(function (i) {
      count[i] = (count[i] || 0) + 1
    })
    let loaded = (count[true]) ? count[true] : 0
    // progress events
    if (loaded > this.loadProgress_[0]) {
      this.loadProgress_ = [loaded, loadStatusArray.length]
      if (this.widget === 'progressBar') {
        this.element.max = this.loadProgress_[1]
        this.element.value = this.loadProgress_[0]
      }
      if (this.onCustomProgress) this.onCustomProgress.apply(this, this.loadProgress_)
    }
  }
}

/**
 * show
 */
ol.control.Loading.prototype.show = function () {
  if (this.showPanel) {
    this.element.style.display = 'block'
  }
}

/**
 * hide
 */
ol.control.Loading.prototype.hide = function () {
  if (this.showPanel) {
    this.element.style.display = 'none'
  }
}

/**
 * 显示进度详情
 * @returns {*[]|Array|[*,*]|[number,number]}
 */
ol.control.Loading.prototype.progressDetails = function () {
  return this.loadProgress_
}

/**
 * 显示进度条
 * @returns {number}
 */
ol.control.Loading.prototype.progress = function () {
  return this.loadProgress_[0] / this.loadProgress_[1]
}

/**
 * 设置地图
 * @param map
 */
ol.control.Loading.prototype.setMap = function (map) {
  if (this.mapListeners &amp;&amp; this.mapListeners.length > 0) {
    this.mapListeners.forEach(listener => {
      this.getMap().unByKey(listener)
    })
  }
  this.mapListeners.length = 0
  ol.control.Control.prototype.setMap.call(this, map)
  if (map) {
    this.setup()
  }
}

let olControlLoading = ol.control.Loading
export default olControlLoading
</pre>
    </article>
</section>





		</div>
	</div>

	<div class="clearfix"></div>

	

</div>
</div>


    <div class="modal fade" id="searchResults">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Search results</h4>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>


<footer>


	<span class="copyright">
	https://lzw.me.
	</span>

<span class="jsdoc-message">
	Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
	
		on Sun Aug 12th 2018
	
	using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>

<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>

    <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>


<script>
$( function () {
	$( "[id*='$']" ).each( function () {
		var $this = $( this );

		$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
	} );

	$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
		var $this = $( this );

		var example = $this.find( "code" );
		exampleText = example.html();
		var lang = /{@lang (.*?)}/.exec( exampleText );
		if ( lang && lang[1] ) {
			exampleText = exampleText.replace( lang[0], "" );
			example.html( exampleText );
			lang = lang[1];
		} else {
			var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
			lang = langClassMatch ? langClassMatch[1] : "javascript";
		}

		if ( lang ) {

			$this
			.addClass( "sunlight-highlight-" + lang )
			.addClass( "linenums" )
			.html( example.html() );

		}
	} );

	Sunlight.highlightAll( {
		lineNumbers : true,
		showMenu : true,
		enableDoclinks : true
	} );

	$.catchAnchorLinks( {
        navbarOffset: 10
	} );
	$( "#toc" ).toc( {
		anchorName  : function ( i, heading, prefix ) {
			return $( heading ).attr( "id" ) || ( prefix + i );
		},
		selectors   : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
		showAndHide : false,
		smoothScrolling: true
	} );

	$( "#main span[id^='toc']" ).addClass( "toc-shim" );
	$( '.dropdown-toggle' ).dropdown();

    $( "table" ).each( function () {
      var $this = $( this );
      $this.addClass('table');
    } );

} );
</script>



<!--Navigation and Symbol Display-->


<!--Google Analytics-->



    <script type="text/javascript">
        $(document).ready(function() {
            SearcherDisplay.init();
        });
    </script>


</body>
</html>
